var knowledgeCenterDAO = require('../controller/controller.knowledgecenter');
var aliOSS = require('../utils/ali-oss');
var fileUtil = require('../utils/fileUtil')('disk');
/**
 * 知识中心Service
 */
module.exports = {
    getList:function (req, res, next) {
        var params = {};
        var type = req.params.type || 'personal';
        params.fileType = req.query.fileType||'';
        if (type =='personal')
            params.createUid = req.session.uid;
        knowledgeCenterDAO.list(params,function (err, result) {
            var list = [];
            if (result && result.obj){
                list = result.obj;
            }
             next({list:list, moment:require('moment')});
        });
    },
    getDetail:function (req, res, next) {
      knowledgeCenterDAO.get(req.params.rowId,function (err,result) {
          if (err){
              next(err, null);
          }else{
              next(null, {knowledge:result.obj});
          }
      });
    },
    createItem:function (req, res, next) {
        var createUid = req.session.uid;
        var createUser = req.session.userinfo.name;
        fileUtil.uploadSingleFile(req, res, 'file',function (err, fields, file) {
            if (err || !file){
                next(err || {code:400,msg:'file not found.'});
                return;
            }else{
                fields.attachmentName = fields.attachmentName || file.originalname;
                fields.createUid = createUid;
                fields.createUser = createUser;
                var userinfo = req.session && req.session.userinfo;
                var filename = [(userinfo && userinfo.name) || file.fieldname, Date.now(), file.originalname].join('-');
                aliOSS.upload(filename,fileUtil.getFileAsStream(file.path))
                    .then(function (result) {
                        fileUtil.deleteFileFromDisk(file.path);
                        fields.attachmentUrl = result.url;
                        knowledgeCenterDAO.create(fields,function (err, data) {
                            if (err){
                                next({code:500,msg:'form save failed.'});
                            }else{
                                next();
                            }
                        });
                    }).catch(function (err) {
                        fileUtil.deleteFileFromDisk(file.path);
                        console.error(err);
                        next({code:500,msg:'form save failed.'});
                    });
            }
        },['content','tag']);
    },
    deleteByIds:function (req, res, next) {
     var rowIds = req.body.rowIds || [];
     if (rowIds.length>0){
         knowledgeCenterDAO.deleteByIds(rowIds, function (err, result) {
             next(err, result);
         });
     }else{
         next();
     }
    }
}